package com.lyw.GeoLocationClient.ui.adapter;

import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.lyw.GeoLocationClient.R;
import com.lyw.GeoLocationClient.ui.model.LauncherItem;

import java.util.ArrayList;

public class LauncherGridAdapter extends ArrayAdapter<LauncherItem> {

    private Context context;
    private int res;
    private ArrayList<LauncherItem> data;
    public LauncherGridAdapter(Context context, int resource, ArrayList<LauncherItem> objects) {
        super(context, resource, objects);
        this.context = context;
        this.res = resource;
        this.data = objects;
    }


    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View row = convertView;
        ViewHolder holder = null;
        if (row != null) {
            holder = (ViewHolder) row.getTag();
        } else {
            row = ((Activity)context).getLayoutInflater().inflate(res, parent, false);

            holder = new ViewHolder();
            holder.title = (TextView) row.findViewById(R.id.title);
            holder.icon = (ImageView) row.findViewById(R.id.icon);

            row.setTag(holder);
        }

        if (holder != null) {
            holder.title.setText(data.get(position).getTitle());
            holder.icon.setImageResource(data.get(position).getIcon());
        }
        makeItemFitParentHeight(parent, row);
        return row;
    }

    /** 动态调整每个item高度，以便刚好适应整个屏幕 */
    private void makeItemFitParentHeight(ViewGroup parent, View itemView) {
        Resources resources = parent.getContext().getResources();
        // 网格列数
        int numColumns = 2;
        // 网格行数
        int numRows = (int) Math.ceil(1.0 * getCount() / numColumns);
        // 网格垂直分割线的宽度
        int verticalSpacingHeight = (int) resources
                .getDimension(R.dimen.grid_module_verticalSpacing);
        // 父容器的总高度
        int parentHeight = ((ViewGroup) parent.getParent()).getHeight();
        // 计算出条目应有的高度
        int itemHeight = (int) (1.0 * parentHeight / numRows);
        // 减去网格分割线的高度
        itemHeight = itemHeight - verticalSpacingHeight * (numRows - 1);
        // 设置条目的高度
        if (itemHeight > 0) {
            AbsListView.LayoutParams lp = new AbsListView.LayoutParams(
                    AbsListView.LayoutParams.MATCH_PARENT, itemHeight);
            itemView.setLayoutParams(lp);
        }
    }

    class ViewHolder {
        ImageView icon;
        TextView title;
    }
}